import speech_recognition as sr
from aip import AipSpeech
import json
import sys
import requests
import time
import pyttsx3  #将文字转语音的第三方库
# 语言采样
# def writeAudioFile(rate=16000):
#     r=sr.Recognizer();
#     with sr.Microphone(sample_rate=rate) as source:
#         print("请说话：")
#         audio=r.listen(source)
#
#     with open("myaudio.wav","wb") as file:
#         file.write(audio.get_wav_data())
#     print("声音文件录制完毕")

# 使用baidu AI声音转文字
appid="24149978"
apikey="GgttZb3MXFSSYuZHhEiBFqUx"
SecretKey="6UFl8CI1qAj9IEj98hGkxRYq59Pa5uQA"
client=AipSpeech(appid,apikey,SecretKey)
def audioConvertToTxt(rate=16000):
    r=sr.Recognizer();
    with sr.Microphone(sample_rate=rate) as source:
        print("请说话：")
        audio=r.listen(source)
    autiodata=client.asr(audio.get_wav_data(),"wav",rate,{"dev_pid":1536})
    json1=json.dumps(autiodata,ensure_ascii=False)
    myjson=json.loads(json1)
    print(myjson["result"][0])
    return myjson["result"][0]

# 图灵机器人对话
tulingurl="http://openapi.tuling123.com/openapi/api/v2"
appkey="4ee411e75a23472e9721f1d7c9a47e7f"
# tulingurl="http://api.tianapi.com/txapi/robot/index"
# appkey="e51daa13fc3937302ae3a38caed0520f"
def robot1(say="没有听清，请再说一遍"):
    say=audioConvertToTxt()
    jsonParam={
	"reqType":0,
    "perception": {
        "inputText": {
            "text": say
        },
        "inputImage": {
            "url": "imageUrl"
        },
        "selfInfo": {
            "location": {
                "city": "泰安",
                "province": "山东",
                "street": "凤凰路"
            }
        }
    },
    "userInfo": {
        "apiKey": appkey,
        "userId": "tutu"
    }
    }
    res=requests.post(tulingurl,None,jsonParam)
    tulingsay=json.loads(res.text)
    print(tulingsay["results"][0]["values"]["text"])
    txtConvertAudio(tulingsay["results"][0]["values"]["text"])
    return tulingsay["results"][0]["values"]["text"]

# 文字转声音
def txtConvertAudio(data="没有听清楚，请再说一遍"):
    engine=pyttsx3.init();
    rate=engine.getProperty("rate")
    engine.setProperty("rate",rate-66)
    engine.say(data)
    print(data)
    engine.runAndWait()


# robot()